<!--后付费记录-->
<template>
    <div style="height: 100%;">
        <m-page-list
                ref="pageListRef"
                :option="option"
                :page="page"
                :total="total"
                :table-data="tableData"
                :table-loading="tableLoading"
                :page-loading="pageLoading"
                v-model:value="query"
                @h-btn-click="hBtnClick"
                @col-btn-click="colBtnClick"
                @search-data="searchData"
        >
            <template #import>
                <el-upload
                        ref="uploadRef"
                        class="upload-wrap"
                        action=""
                        accept=".xlsx,.xls"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="handleUploadChange"
                >
                    <el-button type="primary" >导入</el-button>
                </el-upload>
            </template>
        </m-page-list>
        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>

        <m-dialog-form ref="mDialogRef" :data="mDialog.data" v-model:show="mDialogShow" :option="mDialog" @confirm="handleConfirm" ></m-dialog-form>
    </div>
</template>

<script setup>
  import {ref,reactive} from 'vue'
  import * as XLSX from 'xlsx'
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  //请求
  import {getAfterPayment, addAfterPayment, editAfterPayment,delAfterPayment,batchAddPriorityPassengers,batchDelAfterPayment,publicPriorityPassengers,batchImportAfterPayment,exportAfterPayment,afterPaymentRefund,getAfterPaymentSchool,processedAllFeedback} from '@/request/api/basicData'
  import {refOpt} from "../const";
  import { readFile} from "../../utils/xlsx";
  import {getAuthority} from "../../utils/permission";
  import {downFile} from "../../utils/utils";
  import {usePageList} from "../../composables/pageList";

  let opts = {
    auth_id: 'after_payment',
    getApi: getAfterPayment,addApi:addAfterPayment,editApi:editAfterPayment,delApi:delAfterPayment,
    idKey: 'row_id',
    // confirmCallback: publicPriorityPassengers,
    // deleteCallback: publicPriorityPassengers
  };

  let {option,page,total,tableLoading,pageLoading,tableData,query,dialogRef,dialogShow,dialogData,dialogOption,isAppend,isDelete,isEdit,
    newData,hBtnClick,colBtnClick,searchData,getDataList,dialogConfirm} = usePageList(opts);

  //开启表格选择
  option.tableSelection = true;
  option.hLBtns = [];
  /*option.hRBtns = [
    {title: '新增',id: 'newData',type: 'primary',event: newData},
    {useSlot: true,slotName: 'import'},
    {title: '批量生成',id: 'newData',type: 'primary',event: () => handleShow('batchBuild')},
    // {title: '批量删除',id: 'newData',type: 'default',event: batchDel}
    {title: '批量删除',id: 'newData',type: 'default',event: () => handleShow('batchDel')},
  ]*/
  option.conditions = [
    {label: '订单编号',type: 'text',field_id: 'out_trade_no',col: 6},
    {...refOpt.school_name,valueKey: ['school_name'],col: 6,rewriteInput: true,refUrl: getAfterPaymentSchool},
    {...refOpt.packag_label_name,valueKey: ['packag_label_name'],label: '套票标签',col: 6,rewriteInput: true},
    {label: '缴费状态',type: 'picklist',field_id: 'is_pay_off',col: 6,options: [
        {name: '未缴费',id: 'false'},
        {name: '已缴费',id: 'true'},
      ]},
    {label: '乘客名称',type: 'text',field_id: 'passengers_name',col: 6},
    {label: '证件号码',type: 'text',field_id: 'identification_no',col: 6},
    {field_id: 'parents_phone',type: 'text',label: '购票人电话',col: 6 },
    {field_id: 'backup_phone',type: 'text',label: '备用电话',col: 6 },
    {field_id: 'student_idcard_no',type: 'text',label: '乘客身份证号',col: 6 },
    {label: '意见反馈标识',type: 'picklist',field_id: 'is_feedback',col: 6,options: [
        {name: '有反馈',id: 'true'},
        {name: '无反馈',id: 'false'},
      ]},
    {label: '已处理标识',type: 'picklist',field_id: 'is_feedback_processed',col: 6,options: [
        {name: '未处理',id: 'false'},
        {name: '已处理',id: 'true'},
      ]},
    {label: '班别',type: 'text',field_id: 'class_',col: 6},
    {label: '车费所属期',type: 'text',field_id: 'fare_period',col: 24},
  ];
  option.cols = [
    {prop: 'out_trade_no', label: '订单编号',},
    {prop: 'passengers_name', label: '乘客名称',},
    {prop: 'identification_no',label: '证件号码' },
    {prop: 'original_price',label: '应收车站客运班车费' },
    {prop: 'cost',label: '实收车站客运班车费' },
    {prop: 'school_name',label: '站点名称' },
    {prop: 'packag_label_name',label: '套票标签' },
    {prop: 'class_',label: '班级' },
    {prop: 'is_pay_off',label: '已付清标识',type: 'bool' },
    {prop: 'paid_amount',label: '支付金额' },
    {prop: 'unpaid_amount',label: '未缴金额' },
    {prop: 'refund_total_amount',label: '退款金额' },
    {prop: 'success_time',label: '支付时间' },
    {prop: 'refund_last_user_name',label: '退款人名' },
    {prop: 'refund_last_time',label: '退款时间' },
    {prop: 'service_time',label: '服务时间' },
    {prop: 'fare_period',label: '车费所属期' },
    {prop: 'payer_name',label: '支付人名' },
    {prop: 'payer_no',label: '支付人编号' },
    {prop: 'sign_pic',label: '签名照片',type: 'picture',hidePic: true, },
    {prop: 'agreement_pic',label: '协议照片' ,type: 'picture',hidePic: true,},
    {prop: 'student_idcard_no',label: '乘客身份证号' },
    {prop: 'parents_phone',label: '购票人电话' },
    {prop: 'backup_phone',label: '备用电话' },
    {prop: 'stop_name',label: '站点名称' },
    {prop: 'get_on_stop',label: '上车站点设置' },
    {prop: 'get_off_stop',label: '下车站点设置' },
    {prop: 'is_allow_expire_pay',label: '允许过期支付',type: 'bool' },
    {prop: 'feedback',label: '意见反馈内容' },
    {prop: 'is_feedback',label: '意见反馈标识',type: 'bool' },
    {prop: 'is_feedback_processed',label: '已处理标识',type: 'bool'},
    {prop: 'feedback_processed_user_id',label: '处理人工号'},
    {prop: 'feedback_processed_user_name',label: '处理人姓名'},
    {prop: 'feedback_processed_user_time',label: '处理时间'},
    {prop: 'abstract_',label: '摘要' },
    {prop: 'input_id',label: '录入员号' },
    {prop: 'input_name',label: '录入员名' },
    {prop: 'input_time',label: '录入时间' },
    {prop: 'modify_id',label: '修改员号' },
    {prop: 'modify_name',label: '修改员名' },
    {prop: 'modify_time',label: '修改时间' },
  ];
  dialogOption.fieldList = [
    {field_id: 'out_trade_no',label: '订单编号',type: 'text',col: 2 ,required: true,editDisabled: true,
        formatter: (value) => `HZF${value}`,
        parser:(value) => value.replace(/HZF\s?|(,*)/g, '')
    },
    {field_id: 'passengers_name',label: '乘客姓名',type: 'text',col: 2 ,required: true },
    {field_id: 'identification_no',label: '证件号码',type: 'text',col: 2 ,required: false },
    {...refOpt.school_name,col: 2,required: true},
    {...refOpt.packag_label_name,col: 2,required: false},
    {field_id: 'class_',label: '班别',type: 'text',col: 2 ,required: true },
    {field_id: 'student_id',label: '乘客学号',type: 'text',col: 2 ,required: false },
    {field_id: 'student_idcard_no',label: '乘客身份证号',type: 'text',col: 2 ,required: false },
    {field_id: 'parents_phone',label: '购票人电话',type: 'text',col: 2 ,required: false },
    {field_id: 'backup_phone',label: '备用电话',type: 'text',col: 2 ,required: false },
    {field_id: 'original_price',label: '应收车站客运班车费',type: 'number',precision: 2,col: 2 ,required: true },
    {field_id: 'cost',label: '实收车站客运班车费',type: 'number',precision: 2,col: 2 ,required: true },
    {field_id: 'fare_period',label: '车费所属期',type: 'text',precision: 2,col: 2 ,required: false },
    {field_id: 'service_time',label: '服务时间',type: 'text',col: 2 ,required: false },
    {field_id: 'stop_name',label: '站点名称',type: 'text',col: 2 ,required: false },
    {field_id: 'get_on_stop',label: '上车站点设置',type: 'text',col: 2 ,required: false },
    {field_id: 'get_off_stop',label: '下车站点设置',type: 'text',col: 2 ,required: false },
    {field_id: 'is_allow_expire_pay',label: '允许过期支付',type: 'bool',col: 2 ,required: false },
    {field_id: 'feedback',label: '意见反馈内容',type: 'textarea',col: 4 ,required: false },
    {field_id: 'is_feedback',label: '意见反馈标识',type: 'bool',col: 2 ,required: false },
    {field_id: 'is_feedback_processed',label: '已处理标识',type: 'bool',col: 2 ,required: false },
    {field_id: 'abstract_',label: '摘要',type: 'text',col: 4  },
  ];

  //批量新增删除弹窗
  let mDialog = ref({
      title: '退款',
      fieldList: [
        {field_id: 'refund_amount', label: '退款金额',type: 'number', precision: 2, col: 3,required: true},
      ],
      data: {}
    }),
    mDialogShow = ref(false),
    mDialogRef = ref(null),
    pageListRef = ref(null);

  //导入excel
  let uploadRef = ref(null)

  //  批量删除
  function batchDel() {
    let rows = pageListRef.value.getSelectionRows();
    if (!rows.length) {
      ElMessage({type: 'warning', message: '请先选择数据行'});
      return;
    }
    ElMessageBox.confirm('确定删除所选数据？', '批量删除', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){
          pageLoading.value = true;
          let list = [];
          rows.forEach(item => {
            let {row_id} = item;
            // list.push(delAfterPayment(row_id))
            list.push(row_id)
          });
          batchDelAfterPayment(list).then(res => {
            if (res.errcode != 0) return;
            pageLoading.value = false;
            ElMessage({
              type: 'success',
              message: `删除成功`,
            });
            getDataList();
          })
          /*Promise.all(list).then(res => {
            pageLoading.value = false;
            let flag = true;
            res.forEach(item => {
              if (item.errcode != 0) flag = false;
            })
            flag && ElMessage({
              type: 'success',
              message: `删除成功`,
            });
            getDataList();
          })*/
        }
      },
    })
  }

  //导入
  const handleUploadChange = async (file) => {

    let dataBinary = await readFile(file.raw);
    let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
    let workSheet = workBook.Sheets[workBook.SheetNames[0]]
    const data = XLSX.utils.sheet_to_json(workSheet);
    const school = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SCHOOL : window.webConfig.webSchool;
    let list = [];
    /*let arr = {
      identification_no: '考号',
      student_idcard_no: '乘客身份证号',
      parents_phone: '购票人电话',
      backup_phone: '备用电话',

      out_trade_no: '订单编号',
      passengers_name: '姓名',
      school_name: '站点',
      packag_label_name: '套票标签名称',
      class_: '班别',
      original_price: '应收车站客运班车费（元)',
      cost: '实收车站客运班车费（元）',
      service_time: '服务时间',
      student_id: '乘客学号',
      fare_period: '车费所属期',
      abstract_: '站点',
      stop_name: '站点名称',
      get_on_stop: '上车站点设置',
      get_off_stop: '下车站点设置'

    }*/
    data.forEach(item => {
      if (!item['姓名'] || !(item['证件号码'] || item['乘客身份证号'] || item['购票人电话'] || item['备用电话'])) return;
      list.push({
        //考号、乘客学号、身份证号、购票人电话任选其一，与乘客姓名捆绑时即可对应乘客的费用缴费
        "identification_no": (item['证件号码'] || '').toString(),
        "student_idcard_no": (item['乘客身份证号'] || '').toString(),
        "parents_phone": (item['购票人电话'] || '').toString(),
        "backup_phone": (item['备用电话'] || '').toString(),

        "out_trade_no": item['订单编号'] || '',
        "passengers_name": item['姓名'] || '',
        "school_name": item['站点'] || school,
        "packag_label_name": item['套票标签名称'] || '',
        "class_": (item['班别'] || '').toString(),
        "original_price": item['应收车站客运班车费（元)'] || 0,
        "cost": item['实收车站客运班车费（元）'] || 0,
        "service_time": item['服务时间'] || '',
        "student_id": item['乘客学号'] || '',
        "fare_period": item['车费所属期'] || '',
        "abstract_": item['站点'] || '',

        "stop_name": item['站点名称'] || '',
        "get_on_stop": item['上车站点设置'] || '',
        "get_off_stop": item['下车站点设置'] || '',
      })
    });
    if (!list.length){
      ElMessage({
        type: 'warning',
        message: '导入数据不能为空'
      });
      return;
    }

    const loadingInstance = ElLoading.service({
      text: '正在导入中，请耐心等待',
      background: '#00000080'
    });

    batchImportAfterPayment(list).then(res => {
      if (res.errcode != 0) return;
      loadingInstance.close();
      let total = res.total || 0
      ElMessageBox.alert(`本次导入${total}条数据`, '导入成功', {
        confirmButtonText: '确定',
      });
      /*ElMessage({
        type: 'success',
        message: '导入成功'
      });*/
      getDataList();
    })

  }

  //导出
  const exportAfterPay = () =>{
    pageLoading.value = true;
    exportAfterPayment(query.value).then(res =>{
      pageLoading.value = false;
      // downFile(res,'后支付记录');
      let {data} = res;
      let filename = decodeURIComponent(res.headers["content-disposition"]);
      filename = filename?.split(`filename*=UTF-8''`)[1]
      downFile(data,filename);
    })
  }

  //显示弹窗
  function handleShow(scope) {
    let {paid_amount,out_trade_no} = scope.row
    let mDia = mDialog.value;
    mDia.data = {refund_amount: paid_amount,out_trade_no}
    mDialog.value = {...mDia};
    mDialogShow.value = true
  }
  //  弹窗确认
  function handleConfirm(obj) {
    let {data,option} = obj;
    if (option.title === '退款') {
      mDialogRef.value.close();
      pageLoading.value = true
      afterPaymentRefund(data).then((res) => {
        pageLoading.value = false
        if (res.errcode !== 0) return
        ElMessage({type: 'success',message: '退款成功'})
        getDataList();
      })
    }
  }

  // 一键处理所有反馈意见
  function bindProcessAll(){
    ElMessageBox.confirm('确定一键处理所有意见反馈？', '一键处理', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){
          pageLoading.value = true;
          processedAllFeedback().then(res => {
            if (res.errcode != 0) return;
            pageLoading.value = false;
            ElMessage({
              type: 'success',
              message: `处理成功`,
            });
            getDataList();
          })
        }
      },
    })
  }

  prepare()
  function prepare() {
    let arr = [],
      after_payment_refund = getAuthority('after_payment_refund');

    isAppend.value && arr.push({title: '新增',id: 'newData',type: 'primary',event: newData})
    isAppend.value && arr.push({useSlot: true,slotName: 'import'})
    arr.push({title: '导出',type: 'primary',event: exportAfterPay})
    isEdit.value && arr.push({title: '一键处理',id: 'processAll',type: 'primary',event: bindProcessAll})
    isDelete.value && arr.push({title: '批量删除',id: 'newData',type: 'default',event: batchDel})
    option.hRBtns = arr;
    after_payment_refund.is_see && option.colBtns.push({title: '退款',id: 'check',type: 'warning',
      filterMethod: (scope) => scope.row.paid_amount > 0 && !scope.row.refund_total_amount,
      event: handleShow })

  }
</script>

<style scoped lang="less">
    .upload-wrap{
        display: inline-block;
        margin: 0 12px;
        vertical-align: bottom;

    }
</style>
